//
//  HJDDietViewController.m
//  常州红房子
//
//  Created by 胡金东 on 16/7/23.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDDietViewController.h"
#import "HJDKnowTableViewCell.h"
#import "HJDKnowModel.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "HJDNewsDetailViewController.h"


@interface HJDDietViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    int pageS;
    int pages;
    int n;
}

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * statuses;

@property (nonatomic,strong) NSString * pageCount;



@end

@implementation HJDDietViewController
-(NSMutableArray *)statuses
{
    if (_statuses ==nil) {
        
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, HJDWidth -10, HJDHeight-100)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
      self.tableView.tableFooterView=[[UIView alloc]init];
    
    NSUserDefaults *defaArr = [NSUserDefaults standardUserDefaults];
       NSMutableArray *idArr = [defaArr objectForKey:@"IDArr"];
    NSString *str = [defaArr objectForKey:@"index"];
    NSInteger index = [str integerValue];
    NSLog(@"index=%ld,%@",(long)index,idArr[index]);
    self.pageCount = @"1";
    NSString *url = @"/app/newLst.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"pageSize"] = self.pageCount;
    
    params[@"id"] = idArr[index];
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *info = (NSDictionary *)responseObject;
        NSMutableArray *arr = info[@"resultMap"][@"result"];
        NSString *sum = info[@"resultMap"][@"count"];
        NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
        [defa setObject:sum forKey:@"countSum"];
        
        self.statuses = [HJDKnowModel mj_objectArrayWithKeyValuesArray:arr];
        
        [self.tableView reloadData];

        NSLog(@"resu%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error%@",error);
    }];
    
    
    //添加下拉刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
    //    添加上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadOldStatus)];
    
    
    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *page = [defa objectForKey:@"countSum"];
    pageS = [page intValue];
    
    
    //   总页数
    pages = (pageS/10) +1 ;
        NSLog(@"pageS=%dpages=%d",pageS,pages);
    n = 1;

}

-(void)loadNewStatus
{
    NSUserDefaults *defaArr = [NSUserDefaults standardUserDefaults];
    NSMutableArray *idArr = [defaArr objectForKey:@"IDArr"];
    NSString *str = [defaArr objectForKey:@"index"];
    NSInteger index = [str integerValue];
    if (n<1) {
        self.pageCount = [NSString stringWithFormat:@"%d",n];
        NSString *url = @"/app/newLst.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"] = self.pageCount;
        params[@"id"] =idArr[index];
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.tableView.mj_header endRefreshing];

            NSDictionary *info = (NSDictionary *)responseObject;
            NSMutableArray *arr = info[@"resultMap"][@"result"];
           
           NSArray *statuses = (NSMutableArray *)[HJDKnowModel mj_objectArrayWithKeyValuesArray:arr];
            //防止覆盖后面的数据
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,statuses.count)];
            //刷新最新的数据，插入到最前面，防止覆盖后面的数据
            [self.statuses insertObjects:statuses atIndexes:indexSet];
            
            [self.tableView reloadData];
            
            //        NSLog(@"resu%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error%@",error);
        }];

    }else{
        
        [self.tableView.mj_header endRefreshing];
    }
}

-(void)loadOldStatus
{
    NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
    NSString *page = [defaS objectForKey:@"countSum"];
    pageS = [page intValue];
        NSLog(@"pag= %d",pageS);
    
    if (pageS%10 != 0) {
        n += 1;
            NSLog(@"pag= %d",pageS);
    }else{
        n+= 1;
            NSLog(@"pag= %d",pageS);
    }
    if (n <= pages) {
        
        NSUserDefaults *defaArr = [NSUserDefaults standardUserDefaults];
        NSMutableArray *idArr = [defaArr objectForKey:@"IDArr"];
        NSString *str = [defaArr objectForKey:@"index"];
        NSInteger index = [str integerValue];
        
        self.pageCount = [NSString stringWithFormat:@"%d",n];
        NSString *url = @"/app/newLst.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"] = self.pageCount;
        params[@"id"] = idArr[index];
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self.tableView.mj_footer endRefreshing];

            NSDictionary *info = (NSDictionary *)responseObject;
            NSMutableArray *arr = info[@"resultMap"][@"result"];
            
            NSArray *statuses = (NSMutableArray *)[HJDKnowModel mj_objectArrayWithKeyValuesArray:arr];
            [self.statuses addObjectsFromArray:statuses];
            
           
            
            [self.tableView reloadData];
            
                    NSLog(@"resu%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error%@",error);
        }];

        
    }else{
        
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"最后一页了"];
    }

}






-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    HJDKnowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) {
        cell = [[HJDKnowTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    }
    HJDKnowModel *know = self.statuses[indexPath.row];
    
    cell.nameK.text = know.title;
     cell.content.text = know.content;
    if ( [know.hits integerValue] >1000) {
        CGFloat sum = [know.hits integerValue]/ 1000.0;
        cell.sum.text = [NSString stringWithFormat:@"%.1fk",sum];
    }else{
        cell.sum.text = [NSString stringWithFormat:@"%ld",(long)[know.hits integerValue]];
        
        NSLog(@"hits==%ld",(long)[know.hits integerValue]);
    }
    cell.sourceK.text = @"来自武进红房子医院";

    CGSize nameKSize = [cell.nameK.text boundingRectWithSize:CGSizeMake(HJDWidth - 26, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:cell.nameK.font,NSFontAttributeName, nil] context:nil].size;
    CGRect nameKRect = cell.frame;
    nameKRect.size.height = nameKSize.height +126;
    cell.frame = nameKRect;
    
   
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//     NSLog(@"%f",cell.frame.size.height);
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell  *CellH = [self tableView:tableView cellForRowAtIndexPath:indexPath];
       return CellH.frame.size.height;
   
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HJDNewsDetailViewController *detail = [[HJDNewsDetailViewController alloc]init];
    detail.knowModel = self.statuses[indexPath.row];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detail];
    
    [self presentViewController:nav animated:NO completion:nil];
    
}

@end
